<?php
namespace App\Utils;

use App\Models\CompanyInfo;
use QL\QueryList;
use Illuminate\Support\Facades\Log;

class QdsScraper
{
    private $ql;
    private $cookie;
    private $no; //期号
    private $catalog; //类目
    private $companyInfoModel;
    public function __construct($no, $catalog = '')
    {
        $this->ql = QueryList::getInstance();
        $this->no = $no;
        $this->catalog = $catalog;
        $this->companyInfoModel = new CompanyInfo();
    }

    public function setCookie(string $cookie){
        $this->cookie = $cookie;
    }

    public function search($ptotal){

        if (!empty($ptotal)){
            for ($i = 0; $i <= $ptotal; $i++){
                $params = [
                    "brandName" => "",
                    "status" => "all",
                    "applicationId" => "",
                    "applicationName" => "",
                    "agency" => "",
                    "noticeTime" => $this->no,
                    "typeCode" => $this->catalog,
                    "page" => $i,
                    "pageSize" => 20
                ];
                $header['cookie'] = $this->cookie;
                $url = "https://so.quandashi.com/search/notice/search-notice";
                $html = $this->ql->get($url, $params)->getHtml();
                $list = json_decode($html, true);
                if (isset($list['data']['data']['items']) && !empty($list['data']['data']['items'])){

                    foreach ($list['data']['data']['items'] as $item){
                        $item['link'] = $this->fetchImage($item['regNo'], $item['tmName']);
                        $info = $this->fetchContactInfo($item['applicantCn']);
                        if (!empty($info)) $item = array_merge($item, $info);
                        $this->putData($item);
                        echo "Page ".$i.": ".$item['regNo']." ".$item['applicantCn']." ".$item['tmName']."\n";
                    }
                }

            }
        }
    }

    /**
     * 企业基本信息（含企业联系方式）
     * @param $name
     * @return array|mixed
     */
    public function fetchContactInfo($name){

        $result = $info = array();
        $company_info = $this->companyInfoModel->queryCompanyInfo($name);
        if (empty($company_info)) {
            $tianyacha = new Tianyancha();
            $tianyacha->setToken("eab5ec28-886d-4079-99f1-f6b80e00f29a");
            if (stripos($name, '公司') !== false) {
                $info = $tianyacha->getMessageByUrlToken($name);
                if (!empty($info)) {

                    $result['phoneNumber'] = $info['phoneNumber'];
                    $result['legalPersonName'] = $info['legalPersonName'];
                    $result['regLocation'] = $info['regLocation'];
                    $info['original_name'] = $name;
                    $rs = $this->companyInfoModel->insertCompanyInfo($info);
                    if (!$rs) {
                        Log::info("Insert Info Failed:", json_encode($info));
                    }
                }
            }
        }else{
            $result['phoneNumber'] = $company_info['phoneNumber'];
            $result['legalPersonName'] = $company_info['legalPersonName'];
            $result['regLocation'] = $company_info['regLocation'];
        }

        return $result;
    }

    /**
     * 商标名称
     * @param $id
     * @param string $name
     */
    public function fetchImage($id, $name){
        $url = "https://so.quandashi.com/search/notice/notice-detail";
        $params = [
            'id' => $id,
            'issue' => $this->no,
            'name' => $name
        ];
        $header['cookie'] = $this->cookie;
        $link = $this->ql->get($url, $params, $header)->find("body > div.page.pt-search > div.w-center > div.page-detail > div.content > img")->attr("src");
        return $link;
    }

    public function putData($data){
        $data_dir = base_path()."/data";
        if (!is_dir($data_dir)){
            mkdir($data_dir);
        }
        if (!empty($data) && is_array($data)){

            $record['announcementIssue'] = $data['announcementIssue'];
            $record['regNo'] = str_replace("/", '', $data['regNo']);
            $record['tmName'] = $data['tmName'];
            $record['intCls'] = $data['intCls'];
            $record['applicantCn'] = str_replace("/", '', $data['applicantCn']);
            $record['legalPersonName'] = isset($data['legalPersonName'])?$data['legalPersonName']:"";
            $record['phoneNumber'] = isset($data['phoneNumber'])?$data['phoneNumber']:"";
            $record['regLocation'] = isset($data['regLocation'])?$data['regLocation']:"";
            $record['link'] = $data['link'];
            $row = implode(',', $record)."\n";
            $row = mb_convert_encoding($row, 'GBK');
            $datafile = $data_dir."/data.csv";
            if (!file_exists($datafile)){
                file_put_contents($datafile, $row);
            }else{
                file_put_contents($datafile, $row, FILE_APPEND);
            }
            //下载图片
            $filename = $data_dir."/".$record['regNo'].$record['applicantCn'].".jpg";
            if (!empty($data['link'])){
                if(!file_exists($filename)) {
                    file_put_contents($filename, file_get_contents($data['link'], true));
                }
            }else{
                Log::info("Download Image Link Is Empty:".json_encode($data));
            }
        }

    }

    public function dd($data, $is_dump = false){
        if ($is_dump){
            var_dump($data);
        }else{
            print_r($data);
        }
        exit;
    }

}
